/*

  This file is part of Kato Javascript Framework (http://kato.googlecode.com/)

  Copyright (c) 2007, Filip Dreger, Jan Urbański

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Kato Javascript Framework nor the names
        of its contributors may be used to endorse or promote products
        derived from this software without specific prior written
        permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

Kato = {}

Kato.Models = {}
Kato.Views = {}
Kato.UI = {}

Kato.Translations = {}

Kato.Translate = function(text){
	if(Kato.Translations[text]){
		text = Kato.Translations[text]
	} else {
		text = text.replace(/_/g,' ')
	}
	return text
}

Kato.Resize = function(element,mouse_x){
	element = $(element)
	element.original_width = Element.getWidth(element)
	element.original_pointerX = mouse_x
	Kato.Resize.resize_observer = function(event){
		document.body.style.cursor = 'e-resize'
		element.style.width = (element.original_width + Event.pointerX(event) - element.original_pointerX) + 'px'
	}
	Kato.Resize.stop_resizing = function(event){
		document.body.style.cursor = ''
		Event.stopObserving(document.body,'mousemove',Kato.Resize.resize_observer)
		Event.stopObserving(document.body,'mouseup',Kato.Resize.stop_resizing)
	}
	Event.observe(document.body,'mousemove',Kato.Resize.resize_observer)
	Event.observe(document.body,'mouseup',Kato.Resize.stop_resizing)
}


/**
 * Controller is a singleton that dispatches Events to registered Actions.
 * Each Event is published to a topic (identified by a string), and each Action
 * is associated with a Regexp. When an event is dispatched, matching actions
 * are identified and two phases follow:
 *
 *  - first, all the Actions that have 'validate' method are called; if any of them
 *  returns an error (something different than 'true'), an event is considered
 *  to be vetoed and controller does not procede with phase two. Instead, an event of type
 *  ERRORS is queued either on the default error topic or the one pointed by 'error_topic' property
 *  of processed Event.
 *  - if no validation problems occured, each Action is executed, An error at this stage generates
 *  an ERRORS event, but does not stop processing of any further Actions.
 *
 * As any Action can dispatch its own events, the dispatch loop makes sure that
 * executin of Actions is never nested. Events are added to an event queue
 * and processed one after another.
 * *
 * When the event queue is emptied, an event is published to "/kato/repaint". This
 * is intended to use for repainting dirty views.
 *
 *
 */

Kato.Event = Class.create({
        initialize: function(topic, type, payload, error_topic){
            this.topic = topic;
            this.type = type;
            this.payload = payload;
            this.error_topic = error_topic;
        }
    }
)

Object.extend(Kato.Event, {
    REPAINT: 1,
    ERRORS: 2,
    ROW: 3,
    ROWS: 4,
    INIT: 5,
    DEBUG: 6
})




Kato.init = function(){
    Kato.Controller.dispatch(new Kato.Event("/kato/init", Kato.Event.INIT))
}

Kato.Controller = {

    _events: [],
    _actions: [],
    _repaint_event: {
        topic: "/kato/repaint",
        type: Kato.Event.REPAINT
    },

    dispatch:   function (event){
        this._events.push(event)
        if (this._events.length == 1){
            while (this._events.length > 0){
                this._dispatch_single(this._events.shift())
            }
            this._dispatch_single(this._repaint_event);
        }
    },

    _dispatch_single: function(event){
        var error_topic = event.error_topic? error.error_topic : "/kato/errors"
        var l = this._actions.length;
        var actions = []

        // create actions
        for (var r = 0; r < l; r++){
            if (event.topic.match(this._actions[r].topic)){
                var action;
                if (this._actions[r].action.execute){
                    action = this._actions[r].action
                } else {
                    action = new this._actions[r].action
                }
                actions.push(action)
            }
        }

        // validate

        var errors = []
        for (var r = 0; r < actions.length; r++){
            if (actions[r].validate){
                var is_error = actions[r].validate(event)
                if (is_error === true) continue;
                errors.push(error)
            }
        }

        if (errors.length > 0){
            this.dispatch(new Kato.Event(
                    error_topic,
                    Kato.Event.ERRORS,
                    errors
                )
            )
        }

        // dispatch

        for (var r = 0; r < actions.length; r++){
            try {
                actions[r].execute(event)
            } catch (e){
                alert(e)
//                this.dispatch(new Event(error_topic, Kato.Event.ERRORS, [new Kato.Error(e)]))
            }
        }
    },

    add_action:  function (topic, action){
        var l = this._actions.length;
        for (var r = 0; r < l; r++){
            if (this._actions[r].topic === topic && this._actions[r].action === action){
                return this;
            }
        }
        this._actions.push({
            topic: topic,
            action: action
        })
    }
}

Kato.Action = Class.create({
    initialize: function(execute, validate){
        if (execute){
            this.execute = execute
        }
        if (validate){
            this.validate = validate
        }
    },

    create: function(){
        return {
            execute:    this.execute,
            valudate:   this.validate
        }
    }
});

Object.extend(Kato.Action.prototype, {});

Kato.Error = Class.create({
    initialize: function(message){
        this.message = message
    }
});

Kato.Renderer = Class.create({});


Kato.View = Class.create({
    _template: {
        build: true,
        dirty: true,
    },

    initialize: function(id, params){
        this.id = id;
        Object.extend(this, this._template)
        Object.extend(this, params)
        if (this.build){
            document.write("<div id='" + this.id + "'></div>");
            this.element = $(id)
        }

        if (Kato.Views[id]){
            throw ("id already taken");
        }

        Kato.Views[id] = this;
        Kato.Controller.add_action("/kato/repaint", this)
    },

    execute: function(e){
        if (e.type == Kato.Event.REPAINT && this.dirty) {
            this.dirty = false;
            this.render()
            return;
        }        
    },

    render: function(){
        this.element.innerHTML = 
            this._build(this.data);
    },

    _build: function(data){
        var html = ["<h3>Raw data view</h3><table>"]

        html.push("<tr>")
        for (var v = 0; v < data.columns.length; v++){
            html.push("<th>", data.columns[v].column, "</th>");
        }
        html.push("</tr>")

        for (var q = 0; q < data.rows.length; q++){
            html.push("<tr>")
            for (var w = 0; w < data.columns.length; w++){
                html.push("<td>", data.rows[q][w], "</td>");
            }
            html.push("</tr>")
        }
        html.push("</table>")
        return html.join("")
    }
});

Kato.UI.Grid = Class.create(Kato.View, {
    selected_row: undefined,

    row_clicked: function(row, tr){
        try {
            var trs = this.element.getElementsByTagName('tr')
            for (var r = 0; r < trs.length; r++){
                if (trs[r] != tr){
                    trs[r].removeClassName("kato_selected");
                }
            }
            tr.addClassName("kato_selected")
        } catch (e){
            alert(e)
            
        }
        this.selected_row = row;
        Kato.Controller.dispatch(new Kato.Event(
            "/view/" + this.id + "/selection/",
            Kato.Event.ROW,
            {columns: this.data.columns, row: row}
        ))
    },

    save_th_widths:function(){
		this.saved_th_widths = []
		var ths = this.element.getElementsByTagName('th')
		for (var v=0; v < ths.length; v++){
			this.saved_th_widths[v] = ths[v].style.width
		}
	},

	set_th_widths:function(){
		var ths = this.element.getElementsByTagName('th')
		if (!this.saved_th_widths){
			for (var v=0; v < ths.length; v++){
				ths[v].style.width = ths[v].style.width
			}
		} else {
			for (var v=0; v < ths.length; v++){
				if(this.saved_th_widths[v]) {
					ths[v].style.width = this.saved_th_widths[v]
				}
			}
		}
	},

	_build:function(data){
		var built_html = [];
		built_html.push(this.build_header(data))
		built_html.push(this.build_rows(data))
		built_html.push(this.build_footer(data))
        return built_html.join("");
	},

	build_header:function(data){
		var html = ['<div style="overflow: auto"><table class="kato kato_table">\n'];
        var ths = ['<tr>']
        this.number_of_columns = 0;
        for (var v = 0; v < data.columns.length; v++) {
            var vm = v
            ths.push('<th');
            if ((this.column_widths) && (this.column_widths[this.model[vm].column])) {
                ths.push(' style="width: ', this.column_widths[this.model[vm].column])
                if (this.column_widths[this.model[vm].column].match(/\d$/)) {
                     ths.push('px"');
                }
                else {
                    ths.push('"');
                }
            }
            ths.push(' column_index="', vm, '"');
            ths.push('>');
            if (v != this.data.columns - 1) ths.push('<span onmousedown="Kato.Resize(this.parentNode,Event.pointerX(event)); Event.stop(event)" style="position: relative; float: right; height: 100%; width: 10px; cursor:e-resize">&nbsp;</span>')
            ths.push(Kato.Translate(data.columns[vm].column));
//                if (this.params['orderby_'+this.model[vm].column] !== undefined) {
//                    if (this.params['orderby_'+this.columns[vm].column] == 'desc') {
//                        ths += '&nbsp;&#9650;';
//                    } else {
//                        ths += '&nbsp;&#9660;';
//                    }
//                }
            ths.push('</th>');
        }
        html.push(ths.join(""))
        html.push('</tr>')
		return html.join("");
	},

	build_rows:function(data){
		var o = []
		for(var v=0; v< data.rows.length; v++){
			o.push(this.build_row(data.rows[v],v))
		}
		return o.join("");
	},

	build_row:function(row, row_number){
		var o = ''

        if (this.selection_active){
			o += "<tr class='kato_clickable' onclick='Kato.Views." + this.id + ".row_clicked(" + row.toJSON()
			o += ", this)' onmouseout='$(this).removeClassName(\"kato_hover\")' onmouseover='$(this).addClassName(\"kato_hover\")'>\n"
		} else {
			o += "<tr>\n"
		}
		for(var v=0; v<row.length; v++){
			var vm = v
            o += "<td>" + row[v] + "</td>"
		}
		o += "</tr>\n"
		return o
	},

	build_footer:function(data){
		var o = ''
		o += '</table></div>'

		return o;
	},

})

Kato.Model = Class.create({
    _template: {
        id: undefined,
        rows: undefined,
        row: undefined,
        columns: undefined,
        topic: undefined
    },
    
    initialize: function (id, params){
        Object.extend(this, this._template)
        Object.extend(this, params)
        this.id = id;
        Kato.Controller.add_action("/kato/init", this);
        if (!this._topic){
            this._topic = "/model/" + this.id + "/update"
        }
    },

    set_rows: function(rows, columns){
        this.rows = rows;
        if (columns){
            this.columns = columns
        }
        this._send_rows_update()
    },

    set_row: function(row, columns){
        this.row = row;
        if (columns){
            this.columns = columns
        }
        this._send_row_update()
    },

    execute: function (event){
        this._execute(event)
    },

    _execute: function(event){
        if (event.type != Kato.Event.INIT) return;
        this._send_rows_update();
    },

    _send_rows_update: function(){
        Kato.Controller.dispatch(new Kato.Event(this.topic, Kato.Event.ROWS, {columns: this.columns, rows: this.rows}))
    },

    _send_row_update: function(){
        Kato.Controller.dispatch(new Kato.Event(this.topic, Kato.Event.ROW, {columns: this.columns, row: this.row}))
    }
})

/*
Local variables:
show-trailing-whitespace: nil
indent-tabs-mode: t
js2-basic-offset: 8
End:
*/
